package com.ruoyi.common.utils;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.sql.SqlUtil;

/**
 * 分页工具类
 *
 * @author ruoyi
 */
public class PageUtils extends PageHelper {
    /**
     * 设置请求分页数据
     */
    public static void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
    }

    /**
     * 清理分页的线程变量
     */
    public static void clearPage() {
        PageHelper.clearPage();
    }

    /**
     * 获取mybatis plus 的分页对象模型
     *
     * @param pageDomain 分页数据 前台传输
     * @param <T>        实体类
     * @return 分页模型
     */
    public static <T> Page<T> buildPagePlus(PageDomain pageDomain) {
        Page<T> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        String orderField = pageDomain.getOrderByField();
        if (StringUtils.isNotEmpty(orderField)) {
            boolean whetherAsc = pageDomain.whetherAsc();
            if (whetherAsc) {
                page.addOrder(OrderItem.asc(orderField));
            } else {
                page.addOrder(OrderItem.desc(orderField));
            }
        }
        //自动优化 COUNT SQL 是否把 join 查询部分移除
        page.setOptimizeJoinOfCountSql(false);
        return page;
    }

}
